package com.example.qihuibao.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * author : cwwei
 * e-mail : 494545699@qq.com
 * date   : 2022/03/07
 * desc   : 字符串分割进行运算(1+2-3+1*2/3)
 */
public class CalculateUtils {
    private static final char add = '+';
    private static final char del = '-';
    private static final char mul = '×';
    private static final char div = '÷';

    public static Pattern cashierPattern = Pattern.compile("^([1-9]\\d{0,9}|0)(\\.\\d{1,2})?$");//金额

    public static double calculate(String s) {
        List<Character> symbols = new ArrayList<>();
        List<String> values = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        boolean addValue = false;

        //split
        for (Character chr : s.toCharArray()) {
            if (isSymbol(chr)) {
                symbols.add(chr);
                if (!sb.toString().isEmpty()) {
                    values.add(sb.toString());
                }
                sb.setLength(0);
                addValue = false;
            }else {
                sb.append(chr);
                addValue = true;
            }
        }
        if (addValue) {//add last one
            if (!sb.toString().isEmpty()) {
                values.add(sb.toString());
            }
        }
        //check
        if (symbols.size() >= values.size()) {
            return -1;
        }
        int count = 0;
        double[] values2 = new double[values.size()];
        for (String str : values) {
            if (!cashierPattern.matcher(str).matches()) {
                return -1;
            }
            values2[count++] = Double.parseDouble(str);
        }

        List<Character> symbols2 = new ArrayList<>();//for +,-
        //先计算 ×, ÷
        for (int i=0; i<symbols.size(); i++) {
            if (symbols.get(i) == mul) {
                values2[i + 1] = values2[i] * values2[i + 1];
                values2[i] = Double.MAX_VALUE;
            } else if (symbols.get(i) == '÷') {
                values2[i + 1] = values2[i] / values2[i + 1];
                values2[i] = Double.MAX_VALUE;
            }else {
                symbols2.add(symbols.get(i));
            }
        }

        //再筛选 +，- 需要的值
        count = 0;
        double[] values3 = new double[symbols2.size()+1];
        for (double value : values2) {
            if (value != Double.MAX_VALUE) {
                values3[count++] = value;
            }
        }

        count = 0;
        double finalValue = values3[count++];
        for (Character chr : symbols2) {
            if (chr == add) {
                finalValue += values3[count++];
            }else if (chr == del) {
                finalValue -= values3[count++];
            }
        }

        return finalValue;
    }

    public static boolean isSymbol(char s) {
        return s == add || s == del || s == mul || s == div;
    }

}
